package com.yowasa.xiuxian.controller;

import cn.hutool.json.JSONObject;
import com.yowasa.xiuxian.entity.mys.ClickMsgComponent;
import com.yowasa.xiuxian.entity.mys.SendMessage;
import com.yowasa.xiuxian.entity.po.XiuXianExtend;
import com.yowasa.xiuxian.service.ReplyService;
import com.yowasa.xiuxian.service.helper.EmailHelper;
import com.yowasa.xiuxian.service.helper.ExtendHelper;
import com.yowasa.xiuxian.service.helper.MessageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;


@RequestMapping("/main")
@RestController
public class MainController {
    public static final Logger logger = LoggerFactory.getLogger(MainController.class);

    @Autowired
    private ReplyService replyService;

    @Autowired
    private MessageHelper messageHelper;

    @Autowired
    private EmailHelper emailHelper;

    @Autowired
    private ExtendHelper extendHelper;

//    @Autowired
//    private TransactionTaskController transactionTaskController;
    //{
    //    "event": {
    //        "robot": {  // 机器人相关信息
    //            "template": {   // 机器人模板信息
    //                "id": "bot_ea9d3xxxxxx9",
    //                "name": "测试",
    //                "desc": "测试机器人",
    //                "icon": "",
    //                "commands": [
    //                    {
    //                        "name": "/重置",
    //                        "desc": "重置会话"
    //                    }
    //                ]
    //            },
    //            "villa_id": 100001 // 事件所属的大别野 id
    //        },
    //        "type": 2,  // 事件类型
    //        "extend_data": {  // 包含事件的具体数据
    //            "EventData": {
    //                "SendMessage": {  // 不同类型事件有不同的回调数据
    //                    "content": "",
    //                    "from_user_id": 3300034,
    //                    "send_at": 1683275781450,
    //                    "object_name": 1,
    //                    "room_id": 95333,
    //                    "nickname": "kdodjcoclss",
    //                    "msg_uid": "C7TC-71AI-KDN8-MS0I"
    //                }
    //            }
    //        },
    //        "created_at": 1683275781450,  // 事件创建事件
    //        "id": "8ee4c10d-8354-18d7-84df-7e02f034cfd1",
    //        "send_at": 1683275782   // 回调事件
    //    }
    //}


    @RequestMapping("/test")
    @ResponseBody
    public JSONObject test(@RequestBody JSONObject jsonObject,HttpServletRequest request){
        String header = request.getHeader("x-rpc-bot_sign");
        logger.info("接受到的验证签名为：{}",header);
        try {
//            JSONObject repsObject = new JSONObject();
//
//            BufferedReader streamReader = new BufferedReader( new InputStreamReader(request.getInputStream(), "UTF-8"));
//            StringBuilder responseStrBuilder = new StringBuilder();
//            String inputStr;
//            while ((inputStr = streamReader.readLine()) != null){
//                responseStrBuilder.append(inputStr);
//                repsObject = JSONUtil.parseObj(responseStrBuilder.toString());
//            }
            JSONObject repsObject = jsonObject.getJSONObject("event");
            logger.info("------------------------,{}",repsObject);
//            logger.info("mys回调接受到消息：" + event);
//            JSONObject jsonObject = JSONUtil.parseObj(event);
            //消息推送

//            Integer type = event.getType();
            Integer type = (Integer) repsObject.get("type");
            logger.info("---------type---------------,{}",type);

//        JoinVilla	有新用户加入大别野	1
//        SendMessage	用户@机器人发送消息	2
//        CreateRobot	大别野添加机器人实例	3
//        DeleteRobot	大别野删除机器人实例	4
//        AddQuickEmoticon	用户使用表情回复消息表态	5
//        AuditCallback	审核结果回调	6

            // 匹配消息类型，对应不同处理
            switch (type) {
                case 1:
                    //有新用户加入大别野
                    //todo  迎新回复
                    break;
                case 2:
                    //用户@机器人发送消息 指令匹配
                    SendMessage sendMessage = repsObject.getJSONObject("extend_data").getJSONObject("EventData").get("SendMessage", SendMessage.class);
//                    MysVillaAndRoom obj = new MysVillaAndRoom();
//                    obj.setVillaId(sendMessage.getVilla_id());
//                    obj.setRoomId(sendMessage.getRoom_id());
//                    mysVillaRoomMapper.
                    //                    SendMessage sendMessage = event.getExtend_data().getSendMessage();
                    replyService.replyMys(sendMessage);
                    break;
                case 3:
                    //大别野添加机器人实例	3
                    break;
                case 4:
                    //大别野删除机器人实例	4
                    break;
                case 5:
                    //用户使用表情回复消息表态	5
                    break;
                case 6:
                    //AuditCallback	审核结果回调	6
                    break;
                case 7:
                    //ClickMsgComponent	按钮点击回调 7
                    logger.info("按钮点击回调：{}",repsObject);
                    ClickMsgComponent clickMsgComponent = repsObject.getJSONObject("extend_data").getJSONObject("EventData").get("ClickMsgComponent", ClickMsgComponent.class);
                    replyService.clickReplyMys(clickMsgComponent);
                    break;
                default:
                    logger.info("不处理的事件");
                    break;
            }
//            {
//                "message": "",
//                    "retcode": 0 // 如果机器人事件处理成功，retcode应当为0
//            }
            return new JSONObject().put("message","操作成功").put("retcode",0);
        }catch (Exception e){
            logger.error(e.toString());
            e.printStackTrace();
            //这里retcode不返回0，会触发重试
            return new JSONObject().put("message","操作成功").put("retcode",0);
        }finally {
            return new JSONObject().put("message","操作成功").put("retcode",0);
        }
    }

//    5321 463
    @RequestMapping("/send")
    public String send(String msg ,String villaId,Integer roomId){
        logger.info(msg);
        logger.info(villaId);
        SendMessage sendMessage = new SendMessage();
        sendMessage.setVilla_id(villaId);
        sendMessage.setRoom_id(roomId);
        try {
            messageHelper.replyMys(sendMessage,msg);
            return "success";
        }catch (Exception e){
            return "fail";
        }
    }

    @RequestMapping("/sendEmail")
    public String sendEmail(String name ,String type,String num,String msg){
        emailHelper.sendEmali(name,type,num,msg);
        return "suucess";
    }

//    @RequestMapping("/refresh")
//    public String refresh(){
//        transactionTaskController.transactionTask();
//        return "suucess";
//    }

    //    5321 463
    @RequestMapping("/image")
    public String image(String url ,String villaId,Integer roomId){

        logger.info(villaId);
        SendMessage sendMessage = new SendMessage();
        sendMessage.setVilla_id(villaId);
        sendMessage.setRoom_id(roomId);
        try {
            messageHelper.imageSendMys(sendMessage,url);
            return "success";
        }catch (Exception e){
            return "fail";
        }
    }

    //    5321 463
    @RequestMapping("/transaction")
    public String transaction(Long id){
//        return transactionTaskController.test(id);
        XiuXianExtend byAccountId = extendHelper.getByAccountId((long) 2);
        System.out.println(byAccountId.getRough());
        System.out.println(byAccountId.getRough() > 100);
        return "success";
    }

}
